const db = require('../db/index.js')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const config = require('../config.js')

exports.regUser = (req, res) =>{
		const userinfo = req.body
		if(!userinfo.username || !userinfo.password)
			return res.cc('用户名或密码不能为空!')

		const sql = `select * from ev_users where username=?`
		db.query(sql, [userinfo.username], function (err, results) {
			  if (err) 
				return res.cc(err)

			  if (results.length > 0) {
				return res.cc('用户名被占用，请更换其他用户名!' )
			  }

		userinfo.password = bcrypt.hashSync(userinfo.password, 10) // 加密
		
		const sql = 'insert into ev_users set ?'  //入库
		db.query(sql, { username: userinfo.username, password: userinfo.password ,nickname: userinfo.nickname, email:userinfo.email}, function (err, results) {

		  if (err) return res.cc(err)

		  if (results.affectedRows !== 1) 
			return res.cc('注册用户失败，请稍后再试！')
		  
		  res.send({ status: 0, message: '注册成功！' })
		})
	})
}

exports.login = (req, res) =>{
	// console.log(req.body.username)
	const userinfo = req.body
	const sql = `select * from ev_users where username=?`
	db.query(sql,[userinfo.username],function(err,results){
	
		if (err)
			return res.cc(err)
		//注意这里字符串加密判断，未加密的总返回FALSE，如admin123
		const compareResult = bcrypt.compareSync(userinfo.password, results[0].password)
		
		// console.log(compareResult)
		if (results.length !== 1|| !compareResult||results[0].username!=userinfo.username)
			return res.cc('登录失败!')
		
		// TODO：登录成功，生成 Token 字符串
		const user = { ...results[0], password: '', user_pic: '' }
		
		const tokenStr = jwt.sign(user, config.jwtSecretKey, {
		  expiresIn: '10h' // token 有效期为 10 个小时
		})
		console.log(results)
		res.send({
		  status: 0,
		  message: '登录成功！',
		  token: 'Bearer ' + tokenStr,
			userId: results[0].id,
			nickname:results[0].nickname
		})
	})
}
